package xdu.lz.stage2_design_pattern.chapter13_producer_consume_pattern;

import java.util.LinkedList;
import java.util.Queue;

public class MessageQueue {

    private static final int DEFAULT_MAX_LIMIT = 100;

    private final int limit;

    private final Queue<Message> queue;

    public MessageQueue() {
        this(DEFAULT_MAX_LIMIT);
    }

    public MessageQueue(final int limit) {
        this.limit = limit;
        this.queue = new LinkedList<>();
    }

    public void put(final Message message) throws InterruptedException {
        synchronized (queue) {
            //如果队列满了则等待
            while (queue.size() >= limit) {
                queue.wait();
            }
            queue.offer(message);
            //队列中有东西进来了，通知可以消费了
            queue.notifyAll();
        }
    }

    public Message take() throws InterruptedException {
        synchronized (queue) {
            //如果队列为空，则一直等待
            while (queue.isEmpty()) {
                queue.wait();
            }
            //拿出数据
            Message message = queue.poll();
            //通知队列已经取出，队列可以再存了
            queue.notifyAll();
            return message;
        }
    }

}
